﻿using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.EF;
using MaterialDesignExtensions.Controls;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;
using System.Windows.Controls;
using Masuit.Tools.Models;
using EntranceGuardManager.Modules.Main.Views;
using Microsoft.EntityFrameworkCore;
using AJWPFAdmin.Core.Models.EF.Tables;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using AJWPFAdmin.Modules.Common.Views;
using AJWPFAdmin.Services.AppointAPI;
using AJWPFAdmin.Core;
using DocumentFormat.OpenXml.Wordprocessing;

namespace EntranceGuardManager.Modules.Main.ViewModels
{

    public class ExcessiveEmissionsListViewModel : BindableBase, INavigationAware
    {

        private AJTableFetchOptions _fetchOptions;

        public AJTableFetchOptions FetchOptions
        {
            get
            {
                return _fetchOptions;
            }
            set
            {
                SetProperty(ref _fetchOptions, value);
            }
        }

        private List<AJTableColumnItem> _columns;

        public List<AJTableColumnItem> Columns
        {
            get { return _columns; }
            set { SetProperty(ref _columns, value); }
        }

        private AJTableSearchFormConfig _formConfig;

        public AJTableSearchFormConfig FormConfig
        {
            get { return _formConfig; }
            set { SetProperty(ref _formConfig, value); }
        }

        private DelegateCommand<DataGridRow> _loadingRowCmd;
        public DelegateCommand<DataGridRow> LoadingRowCmd =>
            _loadingRowCmd ?? (_loadingRowCmd = new DelegateCommand<DataGridRow>(ExecuteLoadingRowCmd));

        void ExecuteLoadingRowCmd(DataGridRow row)
        {

        }

        private IDialogService _dialogSvc;
        private DbService db;
        private AppointAPISvc _appointAPISvc;
        private SystemConfigKey _apiKey;

        public ExcessiveEmissionsListViewModel(DbService dbIns, AppointAPISvc appointAPISvc, IEventAggregator eventAggregator, IDialogService dialogSvc)
        {

            _dialogSvc = dialogSvc;
            _appointAPISvc = appointAPISvc;
            _apiKey = _appointAPISvc.API.Config.Key;
            //eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>().Subscribe(() => Loading = false);

            FetchOptions = new AJTableFetchOptions
            {
                //ExportFileName = "车辆记录导出",
                FetchOnLoaded = false,
                Handle = async (formCfg, pageCfg) =>
                {
                    var carNo = FormConfig.Schemas
                .FirstOrDefault(p => p.Field == nameof(EmiRiseRecord.CarNo)).Value?.ToString();

                    var color = FormConfig.Schemas
                .FirstOrDefault(p => p.Field == nameof(EmiRiseRecord.Color)).Value as CarPlateColor?;

                    //if ((!string.IsNullOrWhiteSpace(@params.CarNo) && @params.Color == null)
                    //|| (string.IsNullOrWhiteSpace(@params.CarNo) && @params.Color.HasValue))
                    //{
                    //    ExceptionTool.FriendlyError("车牌号和号牌颜色必须同时搜索");
                    //}

                    var dates = FormConfig.Schemas
                        .FirstOrDefault(p => p.Field == nameof(EmiRiseRecord.StartTime))?.Value as ObservableCollection<DateTime?>;

                    var start = dates?.ElementAtOrDefault(0);
                    var end = dates?.ElementAtOrDefault(1);

                    //if (start.HasValue && end.HasValue)
                    //{
                    //    if (start.GetValueOrDefault().Subtract(end.GetValueOrDefault()).TotalDays > 90)
                    //    {
                    //        ExceptionTool.FriendlyError("时间跨度不能超过90天");
                    //    }
                    //}

                    var list = await db.EmiRiseRecords
                    .BetweenInDates(new DateTime?[] { start, end }, p => p.CreateDate)
                    .LikeOrLike(carNo, p => p.CarNo)
                    .IfWhere(() => color.HasValue, p => p.Color == color)
                    .Where(p => p.API == _apiKey)
                    .ToPagedListAsync(pageCfg.Current, pageCfg.PageSize);

                    return new AJTableFetchResult
                    {
                        Total = list.TotalCount,
                        HasNext = list.HasNext,
                        Rows = list.Data
                    };
                }
            };

            var end = DateTime.Today;
            var start = end.AddDays(90).Date;

            var dateRangeSchema = new AJTableSearchFormSchema
            {
                Labels = new string[] { "下发开始日期", "下发结束日期" },
                Field = nameof(EmiRiseRecord.CreateDate),
                Type = AJTableSchemaType.RangePicker,
                Value = new ObservableCollection<DateTime?>(new DateTime?[2] { start, end }),
                IsPopular = true,
            };

            FormConfig = new AJTableSearchFormConfig
            {
                Schemas = new ObservableCollection<AJTableSearchFormSchema>
                {
                    new AJTableSearchFormSchema
                    {
                        Label = "车牌号",
                        Field = nameof(EmiRiseRecord.CarNo),
                        Type = AJTableSchemaType.Input,
                        IsPopular = true,
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "号牌颜色",
                        Field = nameof(EmiRiseRecord.Color),
                        Type = AJTableSchemaType.Select,
                        IsPopular = true,
                        Options = new ObservableCollection<AJTableFormSchemaItemOptions>(CommonUtil.EnumToDictionary<CarPlateColor>(null).Select(p => new AJTableFormSchemaItemOptions
                        {
                            Label = p.Key,
                            Value = p.Value
                        }))
                    },
                    dateRangeSchema
                },
                AdvFilterVisibility = System.Windows.Visibility.Collapsed,
                ExportVisibility = System.Windows.Visibility.Collapsed,
            };

            var columns = new List<AJTableColumnItem>()
            {
                new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.CarNo),
                        Title = "车牌号码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.Color),
                        Title = "车牌颜色",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.VIN),
                        Title = "VIN",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.FuelType),
                        Title = "燃油类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.EmissionStandard),
                        Title = "排放标准",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.ExceedInfo),
                        Title = "超标原因",
                    },
                     new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.OverproofVerifyResult),
                        Title = "超标核实结果",
                    },
                     new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.Remark),
                        Title = "备注信息",
                    },
                      new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.ExceedFlag),
                        Title = "是否解除",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                var flag = (int)val;
                                return flag == 0 ? "未解除" : flag == 1 ? "已解除" : "未核实";
                            }
                        }
                    },
                       new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.StartTime),
                        Title = "下发时间",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd");
                            }
                        }
                    },
                         new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.EndTime),
                        Title = "解除时间",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd");
                            }
                        }
                    },
                         new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.Synchronized),
                        Title = "是否已同步",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "已同步" : "未同步";
                            }
                        }
                    },
            };

            Columns = columns;

            db = dbIns;
        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            //ExecuteGetListCmd();

            await Task.Delay(2000);

            FetchOptions.RequestRefresh(false);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }
    }
}
